import { getToken, setToken, removeToken, setTimeStamp, getUserInfo as getUserInfo1, setUserInfo, removeUserInfo } from '@/utils/auth'
import { login, getUserInfo, getUserDetail } from '@/api/user'
import { resetRouter } from '@/router'
const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, payload) {
    state.token = payload
    // 同步到cookie当中
    setToken(payload)
    setTimeStamp(Date.now())
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, payload) {
    state.userInfo = payload
    setUserInfo(payload)
    console.log(JSON.parse(getUserInfo1()))
  },
  removeUserInfo(state) {
    state.userInfo = {}
    removeUserInfo()
  }
}
// actions是异步的 ajax
const actions = {
  // data指的是用户输入的mobile,password
  async login(context, data) {
    const res = await login(data)
    context.commit('setToken', res)
  },
  async getUserInfo(context) {
    const res = await getUserInfo()
    const res1 = await getUserDetail(res.userId)
    console.log(res)
    context.commit('setUserInfo', { ...res, ...res1 })
    return { ...res, ...res1 }
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
    resetRouter()// 重置路由对象中的路由规则
    context.commit('permission/setRoutes', [], { root: true })
  }
}
export default {
  namespaced: true, // 开启命名空间
  state,
  mutations: mutations,
  actions: actions
}

